package com.estronger.shopmanage.ui.order.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.fragment.FragmentFactory;
import com.estronger.shopmanage.fragment.orderQuery.OrderBaseFragment;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.bean.NumBean;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.utils.Toast;
import com.lidroid.xutils.http.RequestParams;
import com.viewpagerindicator.TabPageIndicator;

/**
 * Created by DingYG on 2017-08-08.
 */

public class OrderQueryActivity extends BaseActivity {
    private View rl_root;// 根布局view
    private ProgressBar pg_bar;
    private ViewPager mainVP;
    private TabPageIndicator indicator;// 页面的title布局
    private TextView tv_title;
    private int currPosition = 0;// 当前显示页面的位置
    // 对应每个页的位置-标题
    private String[] pos = {"0", "1","2","3","4","5"};
    private String[] titleString = {"未接收(0)", "未测量(0)", "未成交(0)",
            "未送货(0)", "未安装(0)", "全部" };
    private String[] titleString2 = { "未接收", "未测量", "未成交",
            "未送货", "未安装", "全部"};
    // 初始化各个View
    private EditText etfSearch;
    private RelativeLayout rlfSearch;
    public static String seaContext = "";
    public static boolean isSearch = false;
    @Override
    protected void init() {
        super.init();
        Tools.initIndexMap();
    }

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = View.inflate(this, R.layout.layout_activity_orderquery, null);
        setContentView(rl_root);

        pg_bar = (ProgressBar) findViewById(R.id.progressBar1);
        mainVP = (ViewPager) findViewById(R.id.query_vp);
        indicator = (TabPageIndicator) findViewById(R.id.category_query);
        etfSearch = (EditText) rl_root.findViewById(R.id.etfInputSea);
        rlfSearch = (RelativeLayout) rl_root.findViewById(R.id.rlfSearching);
        tv_title = (TextView) findViewById(R.id.ab_title);
        tv_title.setText("预订单查询");
    }
    // 主要是做子页面切换的监听事件
    @Override
    protected void initAction() {
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(final int position) {
                currPosition = position;
                getTitleNum();
                MyApplication.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        OrderBaseFragment.isRestart = true;
                        etfSearch.setText("");
                        FragmentFactory.createOrderFragement(position);
                    }
                }, 1000);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        mainVP.setAdapter(new QueryAdpater(getSupportFragmentManager()));
        indicator.setViewPager(mainVP);
        indicator.onPageSelected(0);
        indicator.setSmoothScrollingEnabled(true);
        etfSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                seaContext = etfSearch.getText().toString();
            }
        });
        etfSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (seaContext.equals("")) {
                        Toast.show(OrderQueryActivity.this, "搜索的内容不能为空!", Toast.LENGTH_SHORT);
                    } else {
                        isSearch = true;
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(etfSearch,InputMethodManager.SHOW_FORCED);
                        imm.hideSoftInputFromWindow(etfSearch.getWindowToken(), 0);
                        Tools.indexMap.put(String.valueOf(getCurrPosition()), 1);
                        FragmentFactory.createOrderFragement(getCurrPosition()).loadData(true,
                                pos[getCurrPosition()]);
                    }
                    return true;
                }
                return false;
            }
        });
        rlfSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (seaContext.equals("")) {
                    Toast.show(OrderQueryActivity.this, "搜索的内容不能为空!", Toast.LENGTH_SHORT);
                    return;
                } else {
                    isSearch = true;
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(etfSearch,InputMethodManager.SHOW_FORCED);
                    imm.hideSoftInputFromWindow(etfSearch.getWindowToken(), 0);
                    Tools.indexMap.put(String.valueOf(getCurrPosition()), 1);
                    FragmentFactory.createOrderFragement(getCurrPosition()).loadData(true,
                            pos[getCurrPosition()]);
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getTitleNum();
        OrderBaseFragment.isRestart = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    /**页面里有多少条目
     */
    public void setIndicatorTitle(int position, long size) {
        LinearLayout layout = ((LinearLayout) indicator.getChildAt(0));
        TextView tv = (TextView) (layout.getChildAt(position));
        tv.setText(titleString2[position] + "(" + size + ")");
    }

    // fragment的适配器
    private class QueryAdpater extends FragmentStatePagerAdapter {

        public QueryAdpater(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titleString[position];
        }

        @Override
        public OrderBaseFragment getItem(int position) {
            OrderBaseFragment fragment = FragmentFactory.createOrderFragement(position);
            return fragment;
        }

        @Override
        public int getCount() {
            return titleString.length;
        }
    }

    // 获取各种状态的预订单数量数量
    public void getTitleNum() {
        MyHandler myHandle = new MyHandler();
        Message msg = new Message();
        myHandle.handleMessage(msg);
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //获取订单详细信息
            RequestParams params = new RequestParams();
            params.addBodyParameter("sf_action", "getpreordcount");
            params.addBodyParameter("usercode", MyApplication.getUserCode());
            connect(params, NetManager.ORDERQUERY_NUM);
        }
    }

    // 根据visible设置进度小圆圈是否显示
    public void setProgresVisible(boolean visi) {
        if (visi) {
            pg_bar.setVisibility(View.VISIBLE);
        } else {
            pg_bar.setVisibility(View.INVISIBLE);
        }
    }
    public int getCurrPosition() {
        return currPosition;
    }

    public View getRoot() {
        return rl_root;
    }

    /*
     * 每次联网成功都会调用，根据code区别请求的sf_action
     */
    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        // 获取任务数量
        if (NetManager.ORDERQUERY_NUM == code) {
            NumBean bean = Tools.getOrderNum(result);
            if(bean != null){
                setIndicatorTitle(0, bean.getUnReceive());
                setIndicatorTitle(1, bean.getUnMeasure());
                setIndicatorTitle(2, bean.getUndeal());
                setIndicatorTitle(3,bean.getUndeliver());
                setIndicatorTitle(4,bean.getUnistall());
            }
        }
    }
    @Override
    protected void onDestroy() {
        FragmentFactory.clearOrderQuery();
        super.onDestroy();
    }
}
